using System;
using System.ComponentModel;
using System.Globalization;
using System.Net;

namespace Framework.Library.Core.Utils.Converters
{
    public class IPAddressTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof (string))
                return true;

            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof (string))
                return true;

            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
                                         Type destinationType)
        {
            if (destinationType == typeof (string) && value != null)
                return value.ToString();

            return base.ConvertTo(context, culture, value, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object data)
        {
            if (data != null && data.GetType() == typeof (string))
            {
                IPAddress ipAddress = IPAddress.Parse(data.ToString());

                return ipAddress;
            }

            return base.ConvertFrom(context, culture, data);
        }
    }
}